<?php

namespace App\Http\Controllers\Bap;
use App\Models\Currency;
use App\Models\CurrencyLog;
use App\Models\Entrust;
use App\Models\Turn;
use App\Models\Order;
use App\Models\Property;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Cloud;
use Exception;
use DB;
use Illuminate\Support\Facades\Redis;
use App\Library\Orders\Orders;



/**
 * 货币管理
 */
class CurrencyController extends Controller
{
    /**
     * 验证货币方法
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/13
     * @access public
     * @param  int    id    货币主键ID
     * @return json
     */
    public function currency_verify($id)
    {
        //条件数组
        $where['id'] = $id;
        $where['pay_switch'] = 1;
        $where['buy_switch'] = 1;
        //查询
        $infos = Currency::where($where)->first();
        //未找到
        if (!$infos) {
            return respF(1031);
        }

        return $infos;
    }

    /**
     * 获取本位币ID
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/13
     * @access public|private|protected
     * @param  mixed    name    comment
     * @param  int    name    comment
     * @param  string    name    comment
     * @param  bool       name    comment
     * @param  array   name    comment
     * @return void|int|string|boolean|array        comment
     */
    public function get_standard()
    {
        $map['is_standard'] = 1;
        $map['pay_switch'] = 1;
        $map['buy_switch'] = 1;

        $currency_info = Currency::where($map)->first(['id']);

        if (!$currency_info){
            return respF(2003);
        }

        return $currency_info->id;
    }
    /**
     * 货币行情
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/13
     * @access public
     * @param  int    id    货币主键ID
     * @return json
     */
	public function currency_market(Request $request)
	{
        //验证必传参数
        if (!$request->has('cid','uid')) {
            return respF(1003);
        }
        $cid = $request->get('cid');
        $uid = $request->get('uid');
        $type = $request->get('type');
        $list = array();

        $currency_info = $this->currency_verify($cid);

        //当前委托 type=1已成交  type=2未成交和部分成交 type=3 已撤销
        if(empty($type)){
            $type = 1;
        }
        $where['uid'] = $uid;
        $where['cid'] = $cid;

        switch ($type){
            case 1:
                $where['status'] = 3;
                $entrust = Entrust::where($where)->orderBy('id','desc')->take(10)->get();
                break;
            case 3:
                $entrust = Entrust::where($where)->whereIn('status', [4, 5])->orderBy('id','desc')->take(10)->get();
                break;
            case 2:
                $entrust = Entrust::where($where)->whereIn('status', [1, 2])->orderBy('id','desc')->take(10)->get();
                break;
            default:
                return respF(1006);
        }

        if ($entrust){
            $list['entrust'] = array_reverse($entrust->toArray());
        }else{
            $list['entrust'] = array();
        }
        //最佳买价
        $list['buy_best'] = (float)$currency_info->official_price;
        $where1['cid'] = $cid;

        $infos1 = Entrust::where($where1)->whereIn('status',[1,2])->orderBy('price','asc')->first(['price']);
        
        if ($infos1){
            $list['buy_best'] = (float)$infos1->price;
        }
        //最佳卖价
        $list['sell_best'] = (float)$currency_info->official_price;

        $infos4 = Entrust::where($where1)->whereIn('status',[1,2])->orderBy('price','desc')->first(['price']);

        if ($infos4){
            $list['sell_best'] = (float)$infos4->price;
        }
        //买卖手续费
        $list['buy_fee'] = $currency_info->buy_fee;
        $list['sell_fee'] = $currency_info->sell_fee;

		return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $list]);
    }

    /**
     * 货币列表
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/13
     * @access public
     * @return json  货币列表集合
     */
    public function currency_list(Request $request)
    {
        $where['online_switch'] = 1;
        $where['pay_switch'] = 1;
        $where['buy_switch'] = 1;

        $data = Currency::where($where)->where('is_standard','!=',1)
           ->orderBy('orderby','asc')->get(['id','logo','name','name_en','orderby']);
        
        if (!$data) {
            $data = array();
            return view('api/currency/currency_list', compact('data','uid'));
        }

        return view('api/currency/currency_list', compact('data','uid'));
    }


    /**
     * 资产信息
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/13
     * @access public
     * @param  int    uid    用户ID
     * @param  int    type   类型 1本位币  2交易货币
     * @param  int    cid    货币ID
     * @return  json         资产信息
     */
    public function property_info(Request $request)
    {
        $info = $request->all();

        if (empty($info['type'])||empty($info['uid'])){
            return respF(1003);
        }

        if ($info['type']==1) {//本位币
            $where['cid'] = $this->get_standard();
        } else {//当前买卖货币
            
            if (empty($info['cid'])) {
                return respF(1004);           
            }

            $this->currency_verify($info['cid']);
            $where['cid'] = $info['cid'];
        }

        $where['uid'] = $info['uid'];
        $infos = Property::where($where)->first(['balance','blocked','total']);

        if (!$infos) {
            $infos = [
                'balance'=>0,
                'blocked'=>0,
                'total'=>0,
            ];
        }

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $infos]);
    }
    /**
     * 资产管理
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/14
     * @access public
     * @param  int    uid    用户ID
     * @return  json         资产列表
     */
    public function property_list(Request $request)
    {
        $info = $request->all();

        if (empty($info['uid'])) {
            return respF(1003);
        }

        $where['uid'] = $info['uid'];
        $infos = Property::where($where)->get(['balance','blocked','total']);

        if (!$infos) {
            return respF(1005);
        }

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $infos]);
    }

    /**
     * 生成委托单
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/13
     * @access public
     * @param  mixed    name    comment
     * @param  int    name    comment
     * @param  string    name    comment
     * @param  bool       name    comment
     * @param  array   name    comment
     * @return void|int|string|boolean|array        comment
     */
    public function entrust_create(Request $request)
    {
        $info = $request->all();
        if(empty($info['uid'])) {
            return view('api/currency/currency_list');
        }

        if (empty($info['password'])||empty($info['type'])||empty($info['uid'])||empty($info['price'])
            ||empty($info['num']) ||empty($info['cid'])) {
            return ['msg'=>'字段缺失','status'=>0];
        }

        if((float)$info['num']>1000000||(float)$info['price']>10000000
            ||(float)($info['price']*$info['num'])>100000000000) {
            return ['msg'=>'金额输入过多','status'=>0];
        }
        //验证密码
        $where_u['pay_pass'] = md5($info['password']);
        $where_u['id'] = $info['uid'];

        $user_info = User::where($where_u)->first();

        if (empty($user_info)) {
            return ['msg'=>'支付密码错误','status'=>0];
        }

        if ($user_info->real_status != 2) {
            return ['msg'=>'实名认证未通过','status'=>0];
        }

        $c_info = $this->currency_verify($info['cid']);//验证货币信息

        if($c_info->is_standard == 2) {
            if ((float)$info['num']>$c_info->total) {
                return ['msg'=>'数量超过平台发行总量','status'=>0];
            }
        }

        $data = array();
        if ($info['type']==1) {//买入委托单
            $where['cid'] = $this->get_standard();
            $where['uid'] = $info['uid'];
            $data['type'] = 3;
            //买家冻结手续费用加上买入所需要的钱
            $s_p = bcmul(bcmul($info['num'], $info['price'], 8), $c_info->buy_fee/100, 8);
            $p_num = bcmul($info['num'], $info['price'], 8)+$s_p;
        } elseif ($info['type']==2) {//卖出委托单
            $s_p = bcmul(bcmul($info['num'], $info['price'], 8), $c_info->sell_fee/100, 8);

            $where['cid'] = $info['cid'];
            $where['uid'] = $info['uid'];
            $data['type'] = 4;
            $p_num = (float)$info['num'];

        } else {
            return ['msg'=>'字段缺失','status'=>0];
        }
        //查询资产
        $user_property = Property::where($where)->first();

        if (empty($user_property) || $user_property->balance < $p_num) {
            return ['msg'=>'资产不足','status'=>0];
        }
        //组装数据
        $data['uid'] = $info['uid'];
        $data['cid'] = $info['cid'];
        $data['number_no'] = get_microtimes('WTD');
        $data['price'] = $info['price'];
        $data['num'] = $info['num'];
        $data['status'] = 1;
        $data['deal'] = 0;
        $data['proc'] =$s_p;
        //更改资产数据
        try {
            //开启事务
            DB::beginTransaction();
            $e_id = Entrust::insertGetId($data);
            $user_property->increment('blocked',$p_num);
            $user_property->decrement('balance',$p_num);
            $re = $this->pair_deal($e_id);
            if ($re!=true)
                return FALSE;
            DB::commit();

            return ['msg' => '提交成功', 'status' => 1];
        } catch (Exception $e) {
            DB::rollback();
            return ['msg'=> '提交失败','status'=> 0];
        }
    }

    /**
     * 匹配订单
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/23
     * @access public
     * @param  mixed    name    comment
     * @param  int    name    comment
     * @param  string    name    comment
     * @param  bool       name    comment
     * @param  array   name    comment
     * @return void|int|string|boolean|array        comment
     */
    public function pair_deal($id)
    {
        if (empty($id)) {
            return false;
        }

        $list = Entrust::where('id',$id)->first();

        if (empty($list)) {
            return false;
        }

        $c_info = $this->currency_verify($list->cid);//交易货币的信息
        $b_c_id = $this->get_standard();
        $where_p['cid'] = $list->cid;

        if ($list->type==3) {  //买入
            $where_p['type'] = 4;
            $list_a = Entrust::where($where_p)->where('price','<=',(float)$list->price)->whereIn('status',[1,2])->first();
            if ($list_a) {
                do{
                    //匹配卖的订单
                    $info_a = Entrust::where($where_p)->where('price','<=',(float)$list->price)
                         ->whereIn('status',[1,2])->orderBy('price','asc')->first();//卖的数据

                    $info_b = Entrust::where('id',$id)->whereIn('status',[1,2])->first();//买家数据

                    if ($info_a &&$info_b) {
                        $num1 = $info_a->num - $info_a->deal;//卖订单剩余量
                        $num2 = $info_b->num - $info_b->deal;//买订单剩余量

                        if ($num1<=$num2) {
                            $num3 = $num1;//当前交易数量
                        } else {
                            $num3 = $num2;//当前交易数量
                        }
                        //修改卖方委托单数据
                        $data1['deal'] = $num3+$info_a->deal;
                        $data1['deal_time'] = time();

                        if ($info_a->num == $data1['deal']) {
                            $data1['status'] =3;//订单完成
                        } else {
                            $data1['status'] =2;
                        }
                        //修改买方委托单数据
                        $data2['deal'] = $num3+$info_b->deal;
                        $data2['deal_time'] = time();

                        if ($data2['deal']==$info_b->num) {
                            $data2['status'] = 3;
                        } else {
                            $data2['status'] = 2;
                        }
                        //修改资产数据
                        //卖方 扣除卖出的货币  得到本位币（价格x数量-手续费）
                        $s_proc = $num3*$info_a->price*($c_info->sell_fee)/100;//卖方手续费
                        $u_proc = ($info_a->price)*($c_info->buy_fee)*$num3/100;//买方扣除USDT手续费
                        $uu_proc = ($info_b->price)*($c_info->buy_fee)*$num3/100;//买方已冻结USDT手续费
                        //卖方资产信息变更
                        //交易币减少  扣除冻结的
                        $where_s1['uid'] = $info_a->uid;
                        $where_s1['cid'] = $info_a->cid;
                        $money_s1 = $num3;
                        //本位币增加
                        $where_s2['uid'] = $info_a->uid;
                        $where_s2['cid'] = $b_c_id;
                        $money_s2 = bcmul($info_a->price, $num3, 8)-$s_proc;
                        //买方资产信息变更
                        //交易币增加
                        $where_u1['uid'] = $info_b->uid;
                        $where_u1['cid'] = $info_b->cid;
                        $money_u1 = $num3;
                        //本位币减少
                        $where_u2['uid'] = $info_b->uid;
                        $where_u2['cid'] = $b_c_id;
                        $money_u2 = bcmul($info_a->price, $num3, 8)+$u_proc;

                        $order_model = new Orders();
                        //买方
                        try {
                            //开启事务
                            DB::beginTransaction();
                            //检查用户资产信息
                            $user_p = $order_model->check_balance($info_b->uid,$info_b->cid);
                            if (!$user_p)
                                return FALSE;
                            //卖的委托单信息更改
                            $info_a->update($data1);
                            //买的委托单信息更改
                            $info_b->update($data2);
                            Property::where($where_s1)->decrement('blocked',$money_s1);
                            Property::where($where_s1)->decrement('total',$money_s1);
                            Property::where($where_s2)->increment('balance',$money_s2);
                            Property::where($where_s2)->increment('total',$money_s2);
                            Property::where($where_u1)->increment('balance',$money_u1);
                            Property::where($where_u1)->increment('total',$money_u1);

                            if ((float)$list->price>(float)$info_a->price) {
                                $money_cj = bcmul($list->price-$info_a->price, $num3, 8)-$u_proc+$uu_proc;
                                Property::where($where_u2)->decrement('blocked',$money_u2+$money_cj);
                                Property::where($where_u2)->increment('balance',$money_cj);
                                Property::where($where_u2)->decrement('total',$money_u2);
                            } else {
                                Property::where($where_u2)->decrement('blocked',$money_u2);
                                Property::where($where_u2)->decrement('total',$money_u2);
                            }

                            //生成资产记录和订单信息
                            $re = $order_model->place_order($id,$info_a->id,$info_b->uid,$info_a->uid,$info_a->cid,$info_a->price,$num3,$u_proc,$s_proc,$info_b->number_no,$info_a->number_no);
                            if ($re!=true)
                                return false;
                            DB::commit();

                        } catch (Exception $e) {
                            DB::rollback();
                            return false;
                        }
                    }
                }while(Entrust::where('id',$id)->first()->status==2&&(!empty(Entrust::where($where_p)->where('price','<=',(float)$list->price)->whereIn('status',[1,2])->first())));
            }
            return true;
        } else {//卖委托单   匹配买
            $where_p['type'] = 3;
            $list_a = Entrust::where($where_p)->where('price','>=',(float)$list->price)->whereIn('status',[1,2])->first();
            if ($list_a) {
                do{
                    //匹配买的订单
                    $info_a = Entrust::where('id',$id)->whereIn('status',[1,2])->first();//卖家数据
                    $info_b = Entrust::where($where_p)->where('price','>=',(float)$list->price)->whereIn('status',[1,2])->orderBy('price','desc')->first();//买的数据
                    if ($info_a &&$info_b){
                        $num1 = $info_a->num - $info_a->deal;
                        $num2 = $info_b->num - $info_b->deal;
                        if ($num1<=$num2){
                            $num3 = $num1;
                        }else{
                            $num3 = $num2;
                        }
                        //修改卖方委托单数据
                        $data1['deal'] = $num3+$info_a->deal;
                        $data1['deal_time'] = time();

                        if ($info_a->num == $data1['deal']){
                            $data1['status'] =3;
                        }else{
                            $data1['status'] =2;
                        }
                        //修改买方委托单数据
                        $data2['deal'] = $num3+$info_b->deal;
                        $data2['deal_time'] = time();

                        if ($data2['deal']==$info_b->num){
                            $data2['status'] = 3;
                        }else{
                            $data2['status'] = 2;
                        }
                        //修改资产数据
                        //卖方 扣除卖出的货币  得到本位币（价格x数量-手续费）
                        $s_proc = $num3*$info_b->price*($c_info->sell_fee)/100;//卖方扣除得到本位币的手续费
                        $u_proc = $info_b->price*$c_info->buy_fee*$num3/100;//买房扣除交易货币的手续费
                        //卖方资产信息变更
                        //交易币减少  扣除冻结的
                        $where_s1['uid'] = $info_a->uid;
                        $where_s1['cid'] = $info_a->cid;
                        $money_s1 = $num3;
                        //本位币增加
                        $where_s2['uid'] = $info_a->uid;
                        $where_s2['cid'] = $b_c_id;
                        $money_s2 = $info_b->price*$num3-$s_proc;
                        //买方资产信息变更
                        //交易币增加
                        $where_u1['uid'] = $info_b->uid;
                        $where_u1['cid'] = $info_b->cid;
                        $money_u1 = $num3;
                        //本位币减少
                        $where_u2['uid'] = $info_b->uid;
                        $where_u2['cid'] = $b_c_id;
                        $money_u2 = $info_b->price*$num3+$u_proc;
                        $order_model = new Orders();
                        //买方
                        try {
                            //开启事务
                            DB::beginTransaction();
                            //检查用户资产信息
                            $user_p = $order_model->check_balance($info_b->uid,$info_b->cid);
                            if (!$user_p)
                                return false;
                            //卖的委托单信息更改
                            $info_a->update($data1);
                            //买的委托单信息更改
                            $info_b->update($data2);
                            Property::where($where_s2)->increment('balance',$money_s2);
                            Property::where($where_s2)->increment('total',$money_s2);
                            Property::where($where_u2)->decrement('blocked',$money_u2);
                            Property::where($where_u2)->decrement('total',$money_u2);
                            Property::where($where_u1)->increment('balance',$money_u1);
                            Property::where($where_u1)->increment('total',$money_u1);
                            Property::where($where_s1)->decrement('blocked',$money_s1);
                            Property::where($where_s1)->decrement('total',$money_s1);


                            //生成资产记录和订单信息
                            $re = $order_model->place_order($id,$info_b->id,$info_b->uid,$info_a->uid,$info_a->cid,$info_b->price,$num3,$u_proc,$s_proc,$info_b->number_no,$info_a->number_no);
                            if ($re!=true)
                                return false;
                            DB::commit();
                        } catch (Exception $e) {
                            DB::rollback();
                            return false;
                        }
                    }
                }while(Entrust::where('id',$id)->first()->status==2&&(!empty(Entrust::where($where_p)->where('price','>=',(float)$list->price)->whereIn('status',[1,2])->first())));
            }
            return true;
        }
    }

    public function test()
    {
        $a = collect($this->currency_verify($this->get_standard()));
        dump($a);die;
        $list = Currency::first()->toArray();
        dump($list);
        die;
        $orders_function = new Orders();
        $a = $orders_function->place_order(1,1,1,1,1,1,1,1,1,1,1);
        //$a = $this->pair_deal();
        dump($a);
    }

    /**
     * @author: yanggang
     * @date: 2018/4/8 0008
     * @param Request $request
     * @return array
     */
    public function kline_data(Request $request)
    {
        $id = $request->get('id');//币种ID
        /**
         * 时间区间 默认为1天  1 1分钟，2 5分钟， 3 15分钟， 4 30分钟， 5 1小时， 6 4小时，7 5天， 8 7天， 9 30天
         * 1分钟   查前5个小时的数据
         * 5分钟   查前25个小时的数据
         * 15分钟  查前75个小时的数据
         * 30分钟  查前150个小时的数据
         * 1小时   查前297个小时的数据
         * 4小时   查前1200个小时的数据
         * 1天     查前144天的数据
         * 1天以上 查全部的数据
         */
        $time_type = $request->get('time_type') ?? 0;

        if (empty($id)) {
            return respF(1003);
        }

        if(!(new Currency())->where(['id'=>$id])->first()) {
            return respF(1007);

        }

        $res = (new CurrencyLog())->get_kline_data($id,$time_type);

        $list = [
            'status'=>1,
            'msg'=>'成功',
            'data'=>[
                'id'=>$id,
                'time_type'=>$time_type,
                'data'=>$res
            ]
        ];

        return $list;
    }

    /**
     * 买卖的深度图数据
     * @date 2018/04/03
     * @author yanggang
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function depth_line_data(Request $request)
    {
        $id = $request->get('id');

        if (empty($id)) {
            return respF(1000);
        }

        if(!(new Currency())->where(['id'=>$id])->first()) {
            return respF(1007);

        }

        $buy = Entrust::select(DB::raw('price,( sum(num)-sum(deal) ) as t_num'))
            ->where(['cid'=>$id,'type'=>3])
            ->whereIn('status',[1,2])
            ->groupBy('price')
            ->orderBy('price','DESC')
            ->limit(20)
            ->get()->toArray();

        $sale = Entrust::select(DB::raw('price,( sum(num)-sum(deal) ) as t_num'))
            ->where(['cid'=>$id,'type'=>4])
            ->whereIn('status',[1,2])
            ->groupBy('price')
            ->orderBy('price','ASC')
            ->limit(20)
            ->get()->toArray();

        $buy = array_reverse($buy);
        $num_buy = [];
        $num_sale = [];
        $price_buy = [];
        $price_sale = [];

        foreach ($buy as $item) {
            $num_buy[] = $item['t_num'];
            array_push($price_buy,price_format($item['price']));
        }

        foreach ($sale as $item) {
            $num_sale[] = $item['t_num'];
            array_push($price_sale,price_format($item['price']));
        }

        //虚拟数组
        $fake_arr = [];

        if ($buy && $sale) {
            $buy_high = $price_buy[count($price_buy)-1];
            $sale_lower = $price_sale[0];
            $price_spread  = $sale_lower- $buy_high;//中间差价
            $fake_price = number_format($price_spread / 5,2,'.','');
            
            for ($i=1;$i<5;$i++) {
                $fake_arr[] = $buy_high + $fake_price*$i;
                $num_buy[] = 0;
            }
        }

        $num_arr =  array_merge($num_buy,$num_sale);
        $list = [
            'status'=>1,
            'msg'=>'成功',
            'data'=>[
                'buy'=>$price_buy,
                'sale'=>$price_sale,
                'fake'=>$fake_arr,
                'num'=>$num_arr
            ]
        ];
        return $list;
    }

    /**
     * 买卖的币种行情
     * @author: yanggang
     * @date: 2018/4/8 0008
     * @return array
     */
    public function lasted_list()
    {
        $orders = Currency::with('order')->orderBy('orderby', 'DESC')->get();
        $btc = [];
        $map = [
            'type'=>1,
        ];
        foreach ($orders as $order) {
            $arr = $order->select('id', 'logo', 'name', 'name_en','official_price')->find($order->id)->toArray();
            //成交总量
            $order_count = $order->order()->where($map)->sum('num');
            //最新价
            $lasted_order = $order->order()->where($map)->orderBy('updated_at', 'DESC')->first();
            $lasted_price = $lasted_order['price'] ?? $arr['official_price'];
            //收盘价
            $close_price = (new CurrencyLog())->get_last_close_price($order->id);
            //涨幅
            if (!$close_price || !$lasted_price) {
                $gains = '0%';
            } else {
                $gains = price_format(($lasted_price - $close_price) / $close_price*100).'%';
            }
            $arr['order_count'] = price_format($order_count);
            $arr['lasted_price'] = price_format($lasted_price);
            $arr['gains'] = $gains;
            array_push($btc, $arr);
        }

        return ['status'=>1,'msg'=>'成功','data'=>$btc];
    }

    /**
     *买卖单个币种的走势
     * @author: yanggang
     * @date: 2018/4/8 0008
     * @param Request $request
     * @return array
     */
    public function currency_trend(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            return respF(1003);
        }
        if(!(new Currency())->where(['id'=>$id])->first()){
            return respF(1007);

        }
        $list = Currency::where(['id'=>$id])->first();
        $name = $list['name_en'];
        $lasted_order = Order::where(['cid'=>$id])->orderBy('id','DESC')->first();
        $lasted_price = $lasted_order['price'] ?? $list['official_price'];
        $max = Order::where(['cid'=>$id])->max('price')??$list['official_price'];
        $min = Order::where(['cid'=>$id])->min('price')??$list['official_price'];
        $sum = Order::where(['cid'=>$id])->sum('num')??$list['official_price'];
        //收盘价
        $close_price = (new CurrencyLog())->get_last_close_price($id);
        $open_price = (new CurrencyLog())->getOpenPrice($id);
        //涨幅
        if (!$close_price || !$lasted_price) {
            $gains = '0%';
        } else {
            $gains = number_format(($lasted_price - $close_price) / $close_price*100, 2).'%';
        }
        //振幅
        $time = strtotime(date('Y-m-d'));
        $today_orders = (new CurrencyLog())::where(['cid' => $id, 'time' => $time])->get();
        if (!$today_orders || !$close_price) {
            $swing = '0%';
        } else {
            $today_max_price = $today_orders->max('high_price'); //当日最高价
            $today_min_price = $today_orders->min('lower_price'); //当日最低价
            $swing = number_format(($today_max_price - $today_min_price) / $close_price * 100, 2) . '%';
        }
        //买一
        $buy_first_price = Entrust::where(['cid' => $id, 'type' => 3])
            ->whereIn('status',[1,2])
            ->max('price');
        if (!$buy_first_price) {
            $buy_first_price = 0;
        }
        //卖一
        $sale_first_price = Entrust::where(['cid' => $id, 'type' => 4])
            ->whereIn('status',[1,2])
            ->min('price');
        if (!$sale_first_price) {
            $sale_first_price = 0;
        }
        $data = [
            'name'=>$name,
            'open'=>$open_price,
            'close'=>$close_price,
            'price'=>$lasted_price,
            'max'=>$max,
            'min'=>$min,
            'sum'=>$sum,
            'gains'=>$gains,
            'swing' => $swing,
            'buy_first' => $buy_first_price,
            'sale_first' => $sale_first_price,
            'time'=>date('H:i:s')
        ];
        return ['status'=>1,'msg'=>'成功','data'=>$data];
    }

    /**
     * 支持转入转出的货币列表.
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/5/17
     *
     * @return json 货币列表集合
     */
    public function currency_turn_list(Request $request)
    {
        $uid = $request->get('uid');
        if (empty($uid))
            return respF(1003);
        $where['online_switch'] = 1;
        $where['pay_switch'] = 1;
        $where['buy_switch'] = 1;
        $data = Currency::where($where)
            ->where('is_standard', '!=', 1)
            ->whereIn('name_en', config('config.roll'))
            ->orderBy('orderby', 'asc')->get(['id', 'logo', 'name', 'name_en', 'orderby']);
        if (collect($data)->count() == 0)
            return respF(1009);
        $data = $data->toArray();
        $u_p_ids = Property::where('uid',$uid)->pluck('cid');
        if ($u_p_ids){
            $u_p_ids = $u_p_ids->toArray();
        }else{
            return respF(1015);
        }
        foreach ($data as $k =>$v){
            if (in_array($v['id'],$u_p_ids)){
                $data[$k]['logo'] = config('alioss.host').'/'.$v['logo'];
            }else{
                unset($data[$k]);
            }
        }
        if (count($data)<1)
            return respF(1015);
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }
    /**
     * 转入转出列表
     *
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/17
     * @access public
     * @param  int    uid    用户ID
     * @return array        记录列表
     */
    public function turn_list(Request $request)
    {
        $info  = $request->all();
        if (empty($info['uid'])||empty($info['page']))
            return respF(1003);
        $uid = $info['uid'];
        $page = $info['page']-1;

        if ($page < 0)
            return respF(1022);
        $where['uid'] = $uid;
        if (!empty($info['type'])){
            if (!in_array($info['type'],[1,2]))
                return respF(1003);
            $where['type'] = $info['type'];
        }
        if (!empty($info['cid']))
            $where['type'] = $info['cid'];
        $turns = Turn::where($where)->orderby('created_at','DESC')->paginate(10);
        if (collect($turns)->count() == 0) {
            return respF(1022);
        }else{
            //处理数据
            $data = [];
            foreach ($turns as $key => $val) {
                //if ((float)$val->num >= 10){
                    $data[$key]['cid'] = $val->cid;
                    $data[$key]['c_name'] = $val->currency->name_en;
                    $data[$key]['logo'] = config('alioss.host') . '/' . $val->currency->logo;
                    $data[$key]['num'] = $val->num;
                    $data[$key]['status'] = $val->status;
                    $data[$key]['type'] = $val->type;
                    $data[$key]['created_at'] = $val->updated_at->format('Y-m-d H:i:s');
                //}
            }
            $data = array_merge($data);
            if (collect($data)->count() == 0) {
                return respF(1022);
            }
            $list['status'] = 1;
            $list['msg'] = '查询成功';
            $list['data']['list'] = $data;
            $list['data']['count'] = Turn::where($where)->count();
        }
        return response()->json($list);
    }


}
